package org.changs.nav.ui.nav;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.changs.aplug.interf.OnBackPressedListener;
import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.nav.R;
import org.changs.nav.databinding.ItemQuickSearchBinding;
import org.changs.nav.databinding.MainSearchPoiMainLayoutBinding;
import org.changs.nav.databinding.SearchRecodeItemBinding;
import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.AmapRouteHelper;
import org.changs.nav.delegate.amap.AmapSearchHelper;
import org.changs.nav.mvp.SearchHelper;
import org.changs.nav.ui.set.CollectAddFragment;
import org.changs.nav.ui.set.CollectFragment;

import java.util.Arrays;

import javax.inject.Inject;

import aplug.data.db.CollectInfoHelper;
import aplug.data.db.SearchRecordHelper;
import aplug.data.db.mode.SearchRecord;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 惠安 on 2017/11/23.
 */

public class SearchMainFragment extends BaseMapFragment implements OnBackPressedListener {
    private MainSearchPoiMainLayoutBinding mBinding;
    private SearchRecordAdapter mSearchRecordAdapter;
    private QuickSearchAdapter mQuickSearchAdapter;
    @Inject SearchRecordHelper mSearchRecordHelper;
    @Inject AmapSearchHelper mAmapSearchHelper;
    @Inject AmapRouteHelper mAmapRouteHelper;
    @Inject MapSwitchDelegate mMapSwitchDelegate;
    @Inject CollectInfoHelper mCollectInfoHelper;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.main_search_poi_main_layout, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding.btnGoBack.setOnClickListener(v -> getContext().onBackPressed());
        mBinding.btnGoSearch.setOnClickListener(v -> {
            startFragment(this, SearchingFragment.newInstance());
        });
        //快速搜索
        mQuickSearchAdapter = new QuickSearchAdapter();
        mQuickSearchAdapter.setOnItemClickListener((v, position) -> {
            if (position == 8) {//前往更多界面
                startFragment(this, SearchMoreFragment.newInstance());
            } else if (position >= 3) { //搜索周边
                mAmapSearchHelper.search(this, mQuickSearchAdapter.getData().get(position).name, true);
            } else if (position == 0) {//回家
                routeHomeOrCompany(CollectInfoHelper.HOME_ID);
            } else if (position == 1) {//去公司
                routeHomeOrCompany(CollectInfoHelper.HOME_ID);
            } else if (position == 2) {//前往收藏界面
                startFragment(this, new CollectFragment());
            }
        });
        mBinding.rccQuickSearch.setLayoutManager(new GridLayoutManager(getContext(), 3));
        mBinding.rccQuickSearch.setAdapter(mQuickSearchAdapter);
    }

    private void routeHomeOrCompany(long id) {
        mCollectInfoHelper.findOne(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(collectInfo -> {
                    if (collectInfo.isValid()) {
                        mAmapRouteHelper.calculate(this, collectInfo.getName(),
                                collectInfo.getAddress(), collectInfo.getLat(), collectInfo.getLon());
                    } else {
                        startFragment(this,
                                CollectAddFragment.newInstance((int) id));
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        setupSearchRecordList();
    }

    @Override
    public boolean onBackPressed() {
        mMapSwitchDelegate.switch2Basics();
        return false;
    }

    private void setupSearchRecordList() {
        if (mSearchRecordAdapter == null) {
            mSearchRecordAdapter = new SearchRecordAdapter();
            mSearchRecordAdapter.setOnItemClickListener((view, position) -> {
                SearchRecord searchRecord = mSearchRecordAdapter.getData().get(position);
                mAmapRouteHelper.calculate(this, searchRecord.getName(), searchRecord.getAddress(),
                        searchRecord.getLatitude(), searchRecord.getLongitude());
            });
            mBinding.rccSearchRecordAim.setLayoutManager(new LinearLayoutManager(getContext()));
            mBinding.rccSearchRecordAim.setIAdapter(mSearchRecordAdapter);
            View footView = LayoutInflater.from(getContext()).inflate(R.layout.search_recode_foot,
                    mBinding.rccSearchRecordAim, false);
            mBinding.rccSearchRecordAim.addFooterView(footView);
            footView.setOnClickListener(v ->
                    mSearchRecordHelper.clear()
                            .subscribeOn(Schedulers.io())
                            .subscribe());
        } else {
            mSearchRecordAdapter.getData().clear();
            mSearchRecordAdapter.notifyDataSetChanged();
        }
        mSearchRecordHelper.findAllPoiRecord()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(searchRecords -> {
                    if (searchRecords.size() == 0) {
                        mBinding.vSearchShortcutTip.setVisibility(View.VISIBLE);
                        mBinding.rccSearchRecordAim.setVisibility(View.GONE);
                    } else {
                        mBinding.vSearchShortcutTip.setVisibility(View.GONE);
                        mBinding.rccSearchRecordAim.setVisibility(View.VISIBLE);
                        mSearchRecordAdapter.getData().addAll(searchRecords);
                        mSearchRecordAdapter.notifyDataSetChanged();
                    }
                });
    }

    public static class SearchRecordAdapter extends SimpleAdapter<SearchRecord, SearchRecodeItemBinding> {
        public SearchRecordAdapter() {
            super(R.layout.search_recode_item);
        }

        @Override
        protected void onBindViewHolder(SearchRecodeItemBinding binding, SearchRecord searchRecord, int position) {
            super.onBindViewHolder(binding, searchRecord, position);
            final boolean isNormal = searchRecord.getType() == SearchRecord.TYPE_NORMAL;
            binding.tvAddress.setVisibility(isNormal ? View.GONE : View.VISIBLE);
            binding.tvName.setText(searchRecord.getName());
            if (!isNormal) {
                binding.tvAddress.setText(searchRecord.getAddress());
            }
        }
    }

    public static class QuickSearchAdapter extends SimpleAdapter<SearchHelper.QuickSearchEntry, ItemQuickSearchBinding> {

        public QuickSearchAdapter() {
            super(Arrays.asList(SearchHelper.sQuickSearch), R.layout.item_quick_search);
        }

        @Override
        protected void onBindViewHolder(ItemQuickSearchBinding binding, SearchHelper.QuickSearchEntry quickSearchEntry, int position) {
            super.onBindViewHolder(binding, quickSearchEntry, position);
            binding.tvName.setText(quickSearchEntry.name);
            binding.ivIcon.setImageResource(quickSearchEntry.icon);
        }
    }
}
